import React, { useState, useRef } from 'react';
import {
  ModalSheet,
  ModalSheetHeader,
  ModalSheetBody,
  // ModalSheetFooter, // 暂未使用
} from '../../components/common/ModalSheet';
import type {
  ModalSheetRef,
  SnapPoint,
} from '../../components/common/ModalSheet';
import './SnapPointsDemo.css';

// 🎯 修改1：弹框高度占全屏 - 使用 1 表示全屏高度
const snapPoints: SnapPoint[] = [0, 100, 0.5, -100, 1];
const initialSnap = 4; // 修改为索引4，对应全屏高度 (1)

// 🎯 修改2：预留属性接口
export type ModalPosition =
  | 'left'
  | 'left-center'
  | 'center'
  | 'right-center'
  | 'right';

export interface SnapPointsConfig {
  /** 动态设置宽度 (像素值或百分比字符串) */
  dynamicWidth?: number | string;
  /** 设置水平位置 */
  horizontalPosition?: ModalPosition;
}

/**
 * Snap Points 专门演示页面
 */
export const SnapPointsDemo: React.FC = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [currentSnap, setCurrentSnap] = useState(initialSnap);
  const modalRef = useRef<ModalSheetRef>(null);

  // 🎯 新增：动态配置状态
  const [config, setConfig] = useState<SnapPointsConfig>({
    dynamicWidth: '80%', // 默认宽度80%
    horizontalPosition: 'center', // 默认居中
  });

  const openModal = () => setIsOpen(true);
  const closeModal = () => setIsOpen(false);

  const snapTo = (index: number) => {
    modalRef.current?.snapTo(index);
  };

  const handleSnapChange = (snapIndex: number, _snapValue: SnapPoint) => {
    setCurrentSnap(snapIndex);
  };

  // 🎯 新增：配置更新函数
  const updateWidth = (width: number | string) => {
    setConfig(prev => ({ ...prev, dynamicWidth: width }));
  };

  const updatePosition = (position: ModalPosition) => {
    setConfig(prev => ({ ...prev, horizontalPosition: position }));
    console.log('🎯 位置更新:', position);
  };

  // 🎯 新增：根据位置计算样式和类名
  const getModalStyles = (): React.CSSProperties => {
    const styles = {
      width: config.dynamicWidth,
    };
    console.log('🎯 Modal 样式:', styles);
    return styles;
  };

  // 🎯 新增：根据位置获取CSS类名
  const getModalClassName = (): string => {
    const baseClass = '';
    let className = '';
    switch (config.horizontalPosition) {
      case 'left':
        className = `${baseClass} custom-position-left`;
        break;
      case 'left-center':
        className = `${baseClass} custom-position-left-center`;
        break;
      case 'center':
        className = `${baseClass} custom-position-center`;
        break;
      case 'right-center':
        className = `${baseClass} custom-position-right-center`;
        break;
      case 'right':
        className = `${baseClass} custom-position-right`;
        break;
      default:
        className = `${baseClass} custom-position-center`;
    }
    console.log('🎯 Modal 类名:', className.trim());
    return className.trim();
  };

  return (
    <div className='snap-points-demo'>
      <div className='demo-header'>
        <button className='back-button' onClick={() => window.history.back()}>
          ← Back
        </button>
        <h1>Snap points</h1>
        <p>Sheet with snap points.</p>
      </div>

      <div className='demo-content'>
        <button className='open-button' onClick={openModal}>
          Open sheet
        </button>

        {/* 🎯 新增：配置控制面板 */}
        <div className='config-panel'>
          <h3>配置面板</h3>

          {/* 宽度控制 */}
          <div className='config-group'>
            <label>动态宽度设置：</label>
            <div className='width-controls'>
              <button
                className={`config-btn ${config.dynamicWidth === '60%' ? 'active' : ''}`}
                onClick={() => updateWidth('60%')}
              >
                60%
              </button>
              <button
                className={`config-btn ${config.dynamicWidth === '80%' ? 'active' : ''}`}
                onClick={() => updateWidth('80%')}
              >
                80%
              </button>
              <button
                className={`config-btn ${config.dynamicWidth === '90%' ? 'active' : ''}`}
                onClick={() => updateWidth('90%')}
              >
                90%
              </button>
              <button
                className={`config-btn ${config.dynamicWidth === 600 ? 'active' : ''}`}
                onClick={() => updateWidth(600)}
              >
                600px
              </button>
            </div>
          </div>

          {/* 位置控制 */}
          <div className='config-group'>
            <label>水平位置设置：</label>
            <div className='position-controls'>
              <button
                className={`config-btn ${config.horizontalPosition === 'left' ? 'active' : ''}`}
                onClick={() => updatePosition('left')}
              >
                靠左
              </button>
              <button
                className={`config-btn ${config.horizontalPosition === 'left-center' ? 'active' : ''}`}
                onClick={() => updatePosition('left-center')}
              >
                靠左一点
              </button>
              <button
                className={`config-btn ${config.horizontalPosition === 'center' ? 'active' : ''}`}
                onClick={() => updatePosition('center')}
              >
                居中
              </button>
              <button
                className={`config-btn ${config.horizontalPosition === 'right-center' ? 'active' : ''}`}
                onClick={() => updatePosition('right-center')}
              >
                靠右一点
              </button>
              <button
                className={`config-btn ${config.horizontalPosition === 'right' ? 'active' : ''}`}
                onClick={() => updatePosition('right')}
              >
                靠右
              </button>
            </div>
          </div>

          {/* 当前配置显示 */}
          <div className='config-display'>
            <p>
              <strong>当前配置：</strong>
            </p>
            <p>宽度: {config.dynamicWidth}</p>
            <p>位置: {config.horizontalPosition}</p>
          </div>
        </div>

        <div className='demo-description'>
          <h2>Example content to make the page scrollable...</h2>
          <p>
            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Recusandae
            sint cupiditate eum quibusdam consequuntur quae! Rem error alias
            placeat aliquid qui facere dicta veniam tenetur suscipit? Quibusdam
            eos est similique excepturi officiis sequi maxime sunt blanditiis
            nulla aperiam rem cum totam eligendi eius voluptatem, dolores
            repellendus! Iste accusantium vero, sint ipsam dicta saepe
            laudantium blanditiis et corporis aliquid deleniti quae vitae
            nostrum, repellat illo explicabo accusamus odit pariatur ex.
          </p>
          <p>
            Quae corrupti veritatis voluptates molestiae ipsam beatae sit quia
            aperiam rem! Natus earum quas, quos rerum nisi nostrum deserunt
            voluptatibus perspiciatis? Hic, animi harum quam, fugit explicabo ab
            accusantium laborum iste rem omnis obcaecati quis earum eligendi in
            inventore, mollitia asperiores numquam amet architecto porro at!
          </p>
          <p>
            Aut praesentium, quia architecto ea natus dicta nihil laborum
            tempora animi quas voluptas recusandae adipisci nostrum vero amet,
            nisi temporibus fugit sequi beatae. Natus fugiat ullam nemo neque
            laborum nesciunt, iure totam aut doloribus ea!
          </p>
        </div>
      </div>

      {/* Modal Sheet with Snap Points */}
      <ModalSheet
        ref={modalRef}
        open={isOpen}
        onClose={closeModal}
        snapPoints={snapPoints}
        initialSnap={initialSnap}
        onSnap={handleSnapChange}
        position='bottom'
        style={getModalStyles()} // 🎯 应用动态样式
        className={getModalClassName()} // 🎯 应用位置类名
      >
        <ModalSheetHeader />
        <ModalSheetBody>
          <div className='sheet-content'>
            <div className='controls'>
              <button className='control-button' onClick={() => snapTo(4)}>
                Snap to top
              </button>
              <button className='control-button' onClick={() => snapTo(3)}>
                Snap to -100px from top
              </button>
              <button className='control-button' onClick={() => snapTo(2)}>
                Snap to 50%
              </button>
              <button className='control-button' onClick={() => snapTo(1)}>
                Snap to 100px
              </button>
              <button className='control-button' onClick={() => snapTo(0)}>
                Snap to 0 (close)
              </button>
            </div>

            <div className='snap-info'>
              <h3>🎯 Snap Points 演示</h3>
              <p>
                当前 Snap Point: <strong>{currentSnap}</strong>
              </p>
              <p>
                当前值: <strong>{snapPoints[currentSnap]}</strong>
              </p>
              <div className='instructions'>
                <h4>使用说明:</h4>
                <ul>
                  <li>拖拽顶部的拖拽条来调整高度</li>
                  <li>使用上方的按钮快速跳转到指定位置</li>
                  <li>松手时会自动吸附到最近的点</li>
                </ul>
              </div>
            </div>
          </div>
        </ModalSheetBody>
      </ModalSheet>
    </div>
  );
};

export default SnapPointsDemo;
